package com.hengfoxwolf.commonbase.base
import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import android.os.Build
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.hengfoxwolf.commonbase.base.util.ScreenUtil
import com.hengfoxwolf.commonbase.base.util.LogX
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import java.lang.ref.WeakReference

abstract class BaseActivity<T : ViewDataBinding> : AppCompatActivity(), CoroutineScope by MainScope() {

    protected lateinit var mBinding : T

    private lateinit var mReceiver: BaseReceiver

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (openScreenAdapter()) {
            ScreenUtil.adapterScreen(this, resources.displayMetrics.xdpi, verticalLayout())
        }
        mBinding = DataBindingUtil.setContentView(this, getLayoutId())
        init(savedInstanceState)

        mReceiver = BaseReceiver(this)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            registerReceiver(mReceiver, IntentFilter().apply {
                addAction(BASE_ACTION0)
            }, Context.RECEIVER_EXPORTED)
        } else {
            registerReceiver(mReceiver, IntentFilter().apply {
                addAction(BASE_ACTION0)
            })
        }
    }

    open fun verticalLayout() : Boolean {
        return true
    }

    //是否开启屏幕适配
    open fun openScreenAdapter() : Boolean {
        return false
    }

    override fun onDestroy() {
        super.onDestroy()
        unregisterReceiver(mReceiver)
        ScreenUtil.resetScreen(this)
        mBinding.unbind()
    }

    protected fun getTextColor(colorRes: Int): Int {
        return resources.getColor(colorRes)
    }

    protected fun getDimensionValue(dimension: Int): Int {
        return resources.getDimensionPixelSize(dimension)
    }

    protected fun getDimensionValue2(dimension: Int): Float {
        return resources.getDimension(dimension)
    }

    protected fun getTextContent(contentId: Int): String {
        return resources.getString(contentId)
    }

    abstract fun getLayoutId() : Int

    abstract fun init(savedInstanceState: Bundle?)

    class BaseReceiver(activity: BaseActivity<*>) : BroadcastReceiver() {
        private val mWeakReference = WeakReference(activity)
        override fun onReceive(context: Context?, intent: Intent?) {
            if (context == null || intent == null) {
                return
            }
            when (intent.action) {
                BASE_ACTION0 -> {
                    LogX.d(TAG, BASE_ACTION0)
                }
            }
        }
    }

    companion object {
        const val TAG = "BaseActivity"
        const val BASE_ACTION0 = "com.android.fragmentdemo.base.base.action0"
    }
}